package manage.util.excel;

import m.system.util.DateUtil;
import m.system.util.StringUtil;
import m.system.util.SystemUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;



public class ExcelObject {
	private String name;
	private List<SheetObject> sheets;
	public ExcelObject(String name){
		this.name=name;
		this.sheets= new ArrayList<>();
	}
	public ExcelObject addSheet(SheetObject sheet){
		this.sheets.add(sheet);
		return this;
	}
	private SXSSFWorkbook workBook=null;
	
	public File toExcelFile() throws IOException{
		File f=new File(File.createTempFile("export_excel_",".tmp").getAbsolutePath());
		SystemUtil.println("导出(",this.name,")所创建的临时文件:",f.getAbsolutePath());
		workBook=new SXSSFWorkbook();
		for(int i=0;i<this.sheets.size();i++){
			SheetObject sh=this.sheets.get(i);
			Sheet sheet = workBook.createSheet();
			workBook.setSheetName(i,sh.getName());
			fillBodyCell(sheet,sh);	//填充内容
		}
		FileOutputStream outStream = new FileOutputStream(f);
		workBook.write(outStream);
		outStream.flush();
		outStream.close();
		workBook.close();
		f.deleteOnExit();
		return f;
	}

	/**
	 * 填充内容
	 *  sheet
	 *  fields
	 *  data
	 *  WriteException 
	 *  WriteException
	 */
	private void fillBodyCell(Sheet sheet,SheetObject sh) {
		for(int i=0;i<sh.getRows().length;i++){
			SheetRow sheetRow=sh.getRows()[i];
			Row row = sheet.createRow(i);
			if(null!=sheetRow.getHeight())
				row.setHeight(new Integer(sheetRow.getHeight()*32).shortValue());
			SheetCell[] scs=sheetRow.getCells();
			for(int j=0;j<scs.length;j++){
				SheetCell sheetCell=scs[j];
				if(i==0) sheet.setColumnWidth(j, sheetCell.getWidth()*32);
				org.apache.poi.ss.usermodel.Cell cell = row.createCell(j);
				String type="";
				if(null==sheetCell.getContent()){
					cell.setCellValue("");
				}else if(sheetCell.getContent() instanceof Number){
					cell.setCellValue(Double.parseDouble(String.valueOf(sheetCell.getContent())));
					type="number";
				}else if(sheetCell.getContent() instanceof Date) {
					cell.setCellValue((Date) sheetCell.getContent());
					type = "date";
				}else if(StringUtil.notSpace(sheetCell.getFormat())){
					cell.setCellValue(DateUtil.format((String) sheetCell.getContent(),sheetCell.getFormat()));
					type = "date";
				}else{
					cell.setCellValue(sheetCell.getContent().toString());
				}
				cell.setCellStyle(createCellStyle(sheetCell.getAlign(),type,sheetCell.getFormat(), sheetCell.isHead(),
					sheetCell.isBorderTop(),sheetCell.isBorderRight(),sheetCell.isBorderBottom(),sheetCell.isBorderLeft()));
			}
		}
		for(Integer[] ns : sh.getMergeCells()) {
			sheet.addMergedRegion(new CellRangeAddress(ns[0], ns[1], ns[2], ns[3]));
		}
	}
	private final Map<String,CellStyle> cellStyleMap= new HashMap<>();
	private CellStyle createCellStyle(String align,String type,String format,boolean head,
									  boolean borderTop,boolean borderRight,boolean borderBottom,boolean borderLeft) {
		String colName= align + type + format + head +
				borderTop + borderRight + borderBottom + borderLeft;
		if(null==cellStyleMap.get(colName)){
			Font font = workBook.createFont();
			font.setColor(Font.COLOR_NORMAL);
			CellStyle cellStyle = workBook.createCellStyle();//创建格式
			DataFormat df = workBook.createDataFormat();
			if("number".equals(type)){
				cellStyle.setDataFormat(df.getFormat(format));
			}else if("date".equals(type)){
				cellStyle.setDataFormat(df.getFormat(format));
			}
			cellStyle.setFont(font);
	        //设置自动换行
	        cellStyle.setWrapText(true);
			if(borderTop) cellStyle.setBorderTop(BorderStyle.THIN);//上边框
			if(borderBottom) cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
			if(borderLeft) cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
			if(borderRight) cellStyle.setBorderRight(BorderStyle.THIN);//右边框
	        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
			if("center".equals(align)){
				cellStyle.setAlignment(HorizontalAlignment.CENTER);
			}else if("left".equals(align)){
				cellStyle.setAlignment(HorizontalAlignment.LEFT);
			}else if("right".equals(align)){
				cellStyle.setAlignment(HorizontalAlignment.RIGHT);
			}
			if(head){//设置背景色
				cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
				cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
			}
	        cellStyleMap.put(colName,cellStyle);
		}
		return cellStyleMap.get(colName);
	}


	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}


	public List<SheetObject> getSheets() {
		return sheets;
	}


	public void setSheets(List<SheetObject> sheets) {
		this.sheets = sheets;
	}
}
